package com.qingcheng.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.qingcheng.pojo.goods.Category;
import com.qingcheng.pojo.goods.Sku;
import com.qingcheng.pojo.order.OrderItem;
import com.qingcheng.service.goods.CategoryService;
import com.qingcheng.service.goods.SkuService;
import com.qingcheng.service.order.CartService;
import com.qingcheng.service.order.PreferentialService;
import com.qingcheng.util.CacheKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author:boy
 * @Date:2019/7/18
 * @description:
 * @ModifiedBy:
 */
@Service(interfaceClass = CartService.class)
public class CartServiceImpl implements CartService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Reference
    private SkuService skuService;
    @Reference
    private CategoryService categoryService;
    @Autowired
    private PreferentialService preferentialService;

    public List<Map<String, Object>> findCartList(String username) {
        System.out.println("从redis中提取购物车:" + username);
        List<Map<String, Object>> list = (List<Map<String, Object>>) redisTemplate.boundHashOps(CacheKey.CART_LIST).get(username);
        if (list == null || list.size() == 0) {
            return new ArrayList<Map<String, Object>>();
        }
        return list;
    }

    public void addItem(String username, String skuId, Integer num) {
        //获取用户购物车
        List<Map<String, Object>> cartList = this.findCartList(username);
        boolean flag = false;
        //遍历购物车
        for (Map<String, Object> map : cartList) {
            OrderItem item = (OrderItem) map.get("item");
            if (skuId.equals(item.getSkuId())) {//购物车存在该商品
                if (item.getNum() <= 0) {//商品数量为0，删除
                    cartList.remove(map);
                    break;
                }
                Integer weight = item.getWeight() / item.getNum();//商品重量
                item.setNum(item.getNum() + num);//设置商品数量
                item.setMoney(item.getPrice() * item.getNum());//设置商品总价
                item.setWeight(weight * item.getNum());//设置总重量
                if (item.getNum() <= 0) {//数量小于0 为减少数量
                    cartList.remove(map);//删除购物车项
                }
                flag = true;
                break;
            }
        }
        if (!flag) {//购物车没有此类
            Sku sku = skuService.findById(skuId);
            if (sku == null) {
                throw new RuntimeException("商品不存在");
            }
            if (!"1".equals(sku.getStatus())) {
                throw new RuntimeException("商品状态非法");
            }
            if (num <= 0) {
                throw new RuntimeException("商品数量不合法");
            }
            //新增购物项
            OrderItem orderItem = new OrderItem();
            orderItem.setSkuId(sku.getId());
            orderItem.setSpuId(sku.getSpuId());
            orderItem.setNum(num);
            orderItem.setImage(sku.getImage());
            orderItem.setPrice(sku.getPrice());
            orderItem.setName(sku.getName());
            orderItem.setMoney(orderItem.getPrice() * num);//总价计算
            if (sku.getWeight() == null) {
                sku.setWeight(0);
            }
            orderItem.setWeight(sku.getWeight() * num);//重量计算
            //从缓存中获取商品分类3级
            Category category3 = null;
            //(Category) redisTemplate.boundHashOps(CacheKey.CATEGORY).get(sku.getCategoryId());
            if (category3 == null) {//缓存中无数据
                //数据库查询数据
                category3 = categoryService.findById(sku.getCategoryId());
                //存入缓存中
                redisTemplate.boundHashOps(CacheKey.CATEGORY).put(category3.getId(), category3);
            }
            //设置三级分类id
            orderItem.setCategoryId3(category3.getId());
            //从缓存中查询商品分类2级
            Category category2 = null;
            //(Category) redisTemplate.boundHashOps(CacheKey.CATEGORY).get(category3.getParentId());
            if (category2 == null) {//缓存中无数据
                //数据库查询
                category2 = categoryService.findById(category3.getParentId());
                //存入redis中
                redisTemplate.boundHashOps(CacheKey.CATEGORY).put(category2.getId(), category2);
            }
            //设置二级分类id
            orderItem.setCategoryId2(category2.getId());
            //缓存中获取一级分类id
            Category category1 = null;
            //(Category) redisTemplate.boundHashOps(CacheKey.CATEGORY).get(category2.getParentId());
            if (category1 == null) {//缓存中无数据
                //数据库查询
                category1 = categoryService.findById(category2.getParentId());
                //存入缓存
                redisTemplate.boundHashOps(CacheKey.CATEGORY).put(category1.getId(), category1);
            }
            //设置一级分类id
            orderItem.setCategoryId1(category1.getId());
            Map map = new HashMap();
            map.put("item", orderItem);
            map.put("checked", true);
            //添加购物项
            cartList.add(map);
        }
        //存入缓存
        redisTemplate.boundHashOps(CacheKey.CART_LIST).put(username, cartList);
    }

    public void updateChecked(String username, String skuId, boolean checked) {
        List<Map<String, Object>> cartList = this.findCartList(username);
        boolean isOk = false;
        for (Map<String, Object> map : cartList) {
            OrderItem item = (OrderItem) map.get("item");
            if (item.getSkuId().equals(skuId)) {
                map.put("checked", checked);
                isOk = true;
                break;
            }
            if (isOk) {
                //覆盖原有的购物车
                redisTemplate.boundHashOps(CacheKey.CATEGORY).put(username, cartList);
            }
        }
    }

    public void deleteCheckedCart(String username) {
        List<Map<String, Object>> cartList = this.findCartList(username);
        List<Map<String, Object>> unchecked = cartList.stream()
                .filter(cart -> (Boolean) cart.get("checked") == false)
                .collect(Collectors.toList());
        redisTemplate.boundHashOps(CacheKey.CATEGORY).put(username, unchecked);
    }

    @Override
    public int preferential(String username) {
        List<Map<String, Object>> cartList = this.findCartList(username);
        List<OrderItem> orderItemList = cartList.stream()
                .filter(cart -> (Boolean) cart.get("checked") == true)
                .map(cart -> (OrderItem) cart.get("item"))
                .collect(Collectors.toList());
        //按照分类id分组求和
        Map<Integer, DoubleSummaryStatistics> cartMap = orderItemList.stream()
                .collect(Collectors.groupingBy(OrderItem::getCategoryId3, Collectors.summarizingDouble(OrderItem::getMoney)));
        int allPreMoney = 0;
        for (Integer categoryId : cartMap.keySet()) {
            int money = (int) cartMap.get(categoryId).getSum();
            int premoney = premoney = preferentialService.findPreMoneyByCategoryId((long) categoryId, money);
            allPreMoney += premoney;
        }
        return allPreMoney;
    }

    @Override
    public List<Map<String, Object>> findOrderItem(String username) {
        List<Map<String, Object>> cartList = this.findCartList(username);
        for (Map<String, Object> map : cartList) {
            OrderItem item = (OrderItem) map.get("item");
            Sku sku = skuService.findById(item.getSkuId());
            item.setPrice(sku.getPrice());//更新价格
            item.setMoney(item.getPrice() * item.getNum());//更新总价
        }
        //更新缓存数据
        redisTemplate.boundHashOps(CacheKey.CART_LIST).put(username, cartList);
        return cartList;
    }
}
